package com.stylefeng.guns.modular.train.controller;

import com.alibaba.fastjson.JSON;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.common.constant.MvcResult;
import com.stylefeng.guns.common.persistence.model.*;
import com.stylefeng.guns.config.excel.ExcelExportStylerImpl;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.base.tips.ErrorTip;
import com.stylefeng.guns.core.base.tips.SuccessTip;
import com.stylefeng.guns.core.util.BeanUtils;
import com.stylefeng.guns.modular.system.service.IDictService;
import com.stylefeng.guns.modular.system.service.IQualityGradeRuleService;
import com.stylefeng.guns.modular.train.service.IEmployeeService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.modular.train.service.IPracticePointsService;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.stylefeng.guns.common.constant.Const;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

/**
 * practicePoints控制器
 *
 * @author fengshuonan
 * @Date 2018-02-24 23:31:00
 */
@Controller
@RequestMapping("/practicePoints")
public class PracticePointsController extends BaseController {

    private String PREFIX = "/train/practicePoints/";

    @Autowired
    private IPracticePointsService practicePointsService;
    @Autowired
    private IQualityGradeRuleService qualityGradeRuleService;
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IDictService dictService;

    private static List<PracticePoints> REPEAT = new ArrayList<>();

    /**
     * 跳转到practicePoints首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "practicePoints.html";
    }

    /**
     * 跳转到添加practicePoints
     */
    @RequestMapping("/practicePoints_add")
    public String practicePointsAdd(Model model) {
        List<QualityGradeRule> qualityGradeRuleList = qualityGradeRuleService.getByGradeType(Const.PRACTICE_TRAIN);

        List<Dict> getWays =dictService.getChildByCode(Const.DICT_GET_WAY);

        model.addAttribute("getWays",getWays);
        model.addAttribute("practiceRules",qualityGradeRuleList);
        model.addAttribute("integral",qualityGradeRuleList.get(0).getIntegral());
        return PREFIX + "practicePoints_add.html";
    }

    /**
     * 跳转到修改practicePoints
     */
    @RequestMapping("/practicePoints_update/{practicePointsId}")
    public String practicePointsUpdate(@PathVariable String practicePointsId, Model model) {
        PracticePoints practicePoints = practicePointsService.selectById(practicePointsId);

        List<QualityGradeRule> qualityGradeRuleList = qualityGradeRuleService.getByGradeType(Const.PRACTICE_TRAIN);
        List<Dict> getWays =dictService.getChildByCode(Const.DICT_GET_WAY);

        model.addAttribute("getWays",getWays);
        model.addAttribute("practiceRules",qualityGradeRuleList);
        model.addAttribute("item",practicePoints);
        LogObjectHolder.me().set(practicePoints);
        return PREFIX + "practicePoints_edit.html";
    }

    /**
     * 获取practicePoints列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(Employee employee, Double min, Double max) {
        if(BeanUtils.checkFieldValueNull(employee) && min == null && max == null){
            List<PracticePoints> practicePointss = practicePointsService.selectList(null);
            practicePointss.forEach(n ->{
                if(n.getIssuingTime() != null){
                    n.setStrIssuingTime(Const.df.format(n.getIssuingTime()));
                }
            });
            return practicePointss;
        }

        EntityWrapper<Employee> wrapper = new EntityWrapper<>();
        wrapper.setEntity(employee);
        List<Employee> employees = employeeService.selectList(wrapper);
        Set<String> empCodes = new HashSet<>();
        employees.forEach(e -> empCodes.add(e.getEmpCode()));

        List<PracticePoints> list = new ArrayList<>();
        if(!empCodes.isEmpty()){
            EntityWrapper<PracticePoints> nwWrapper = new EntityWrapper<>();
            nwWrapper.in("emp_code",empCodes);

            if(min != null || max != null){
                min = min == null ? 0.0 : min;
                max = max == null ? 9999.0 : max;

                nwWrapper.between("integral",min,max);
            }

            list = practicePointsService.selectList(nwWrapper);
        }
        list.forEach(n -> {
            if(n.getIssuingTime() != null){
                n.setStrIssuingTime(Const.df.format(n.getIssuingTime()));
            }
        });
        return list;
    }

    /**
     * 新增practicePoints
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(PracticePoints practicePoints) {
        practicePoints.setCreateDate(new Date());
        practicePoints.setDateOrigin(Const.IMPORT_TYPE_SYS);
        practicePointsService.insert(practicePoints);
        return super.SUCCESS_TIP;
    }

    @RequestMapping(value = "/adds")
    @ResponseBody
    public Object adds(@RequestBody PracticePoints[] repeatData) {
        List<PracticePoints> practicePointss = Arrays.asList(repeatData);
        Date now = new Date();
        Map<String, String> gradeAndGradeCodes = qualityGradeRuleService.getMapGradeAndGradeCodeByType(Const.PRACTICE_TRAIN);
        Map<String, Double> points = qualityGradeRuleService.getMapGradeCodeAndIntegralByType(Const.PRACTICE_TRAIN);

        for (PracticePoints practicePoints : practicePointss) {
            practicePoints.setDateOrigin(Const.IMPORT_TYPE_XML);
            practicePoints.setCreateDate(now);

            String grade = gradeAndGradeCodes.get(practicePoints.getPracticeLevel());
            if(StringUtils.isEmpty(grade)){
                practicePoints.setIntegral(0.0);
            }else{
                practicePoints.setPracticeLevelCode(grade);
                practicePoints.setIntegral(points.get(practicePoints.getPracticeLevelCode()));
            }
        }
        practicePointsService.insertBatch(practicePointss);
        return super.SUCCESS_TIP;
    }

    /**
     * 删除practicePoints
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam String practicePointsId) {
        if(practicePointsId.contains(",")){
            List<String> ids = Arrays.asList(practicePointsId.split(","));
            practicePointsService.deleteBatchIds(ids);
        }else{
            practicePointsService.deleteById(practicePointsId);
        }
        return SUCCESS_TIP;
    }

    /**
     * 修改practicePoints
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(PracticePoints practicePoints) {
        practicePointsService.updateById(practicePoints);
        return super.SUCCESS_TIP;
    }

    /**
     * practicePoints详情
     */
    @RequestMapping(value = "/detail/{practicePointsId}")
    @ResponseBody
    public Object detail(@PathVariable("practicePointsId") String practicePointsId) {
        return practicePointsService.selectById(practicePointsId);
    }


    /**
     * 跳转到导入practicePoints
     */
    @RequestMapping("/practicePoints_import")
    public String practicePointsImport() {
        return PREFIX + "practicePoints_import.html";
    }

    /**
     * 导入practicePoints
     */
    @RequestMapping(value = "/import")
    @ResponseBody
    public Object imports(MultipartHttpServletRequest mutReq) {

        ImportParams params = new ImportParams();
        params.setStartRows(0);
        params.setTitleRows(1);

        int count = 2;

        try {
            List<PracticePoints> practicePointss = ExcelImportUtil.importExcel(mutReq.getFile("file").getInputStream(), PracticePoints.class, params);
            Date now = new Date();
            Map<String, String> gradeAndGradeCodes = qualityGradeRuleService.getMapGradeAndGradeCodeByType(Const.PRACTICE_TRAIN);
            Map<String, Double> points = qualityGradeRuleService.getMapGradeCodeAndIntegralByType(Const.PRACTICE_TRAIN);

            Map<String, String> nameAndCode = employeeService.getNameAndCode();
            List<PracticePoints> noRepeat = new ArrayList<>();
            List<PracticePoints> hasNameList = new ArrayList<>();

            for (PracticePoints practicePoints : practicePointss) {
                practicePoints.setDateOrigin(Const.IMPORT_TYPE_XML);
                practicePoints.setCreateDate(now);

                if(StringUtils.isEmpty(practicePoints.getEmpCode())) {
                    //姓名检测
                    if (nameAndCode.containsKey(practicePoints.getEmpName())) {
                        //有该姓名，检测是否重名
                        if (nameAndCode.get(practicePoints.getEmpName()).contains(",")) {
                            //有重名情况
                            practicePoints.setEmpCode(Const.DEFAULT_CODE);
                            REPEAT.add(practicePoints);
                        } else {
                            //无重名、正常插入
                            practicePoints.setEmpCode(nameAndCode.get(practicePoints.getEmpName()));

                            String grade = gradeAndGradeCodes.get(practicePoints.getPracticeLevel());
                            if(StringUtils.isEmpty(grade)){
                                practicePoints.setIntegral(0.0);
                            }else{
                                practicePoints.setPracticeLevelCode(grade);
                                practicePoints.setIntegral(points.get(practicePoints.getPracticeLevelCode()));
                            }

                            noRepeat.add(practicePoints);
                        }
                    } else {
                        throw new Exception("姓名为 " + practicePoints.getEmpName() + " 在员工管理中不存在!");
                    }
                }else{
                    String grade = gradeAndGradeCodes.get(practicePoints.getPracticeLevel());
                    if(StringUtils.isEmpty(grade)){
                        practicePoints.setIntegral(0.0);
                    }else{
                        practicePoints.setPracticeLevelCode(grade);
                        practicePoints.setIntegral(points.get(practicePoints.getPracticeLevelCode()));
                    }
                    hasNameList.add(practicePoints);
                }
                count++;
            }

            //不重复，先插入
            if(noRepeat.size() > 0){
                practicePointsService.insertBatch(noRepeat);
            }
            if(hasNameList.size() > 0){
                practicePointsService.insertBatch(hasNameList);
            }
            //处理重复数据
            if(!REPEAT.isEmpty()){
                MvcResult mvcResult = new MvcResult();
                mvcResult.setData(REPEAT);

                return mvcResult;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return new ErrorTip(400,"第"+ count+"条 " +e.getMessage());
        }

        SuccessTip successTip = super.SUCCESS_TIP;
        successTip.setMessage(String.format("成功插入%d", count-2)  + "条数据");
        return successTip;
    }

    @RequestMapping("/repeat")
    public String repeat(Model model){
        model.addAttribute("repeat", JSON.toJSONString(REPEAT));

        //消费后清空
        REPEAT = new ArrayList<>();
        return PREFIX + "repeat.html";
    }

    /**
     * 导出
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(HttpServletRequest request, HttpServletResponse response) {
        try {
            List<PracticePoints> practicePoints= practicePointsService.selectList(null);
            ExportParams exportParams=new ExportParams("执业资格积分统计表", "执业资格积分统计表");
            exportParams.setStyle(ExcelExportStylerImpl.class);
            exportParams.setTitleHeight((short)14);
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, PracticePoints.class, practicePoints);
            OutputStream outputStream=response.getOutputStream();
            String fileName="执业资格积分统计表.xls";
            response.addHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes(),"ISO-8859-1"));
            workbook.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
